<template>
  <div class="assign-role">
    <div class="role-list">
      <!-- 角色列表 -->
    </div>
    <el-checkbox-group v-model="checkList">
      <el-checkbox v-for="item in list" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
    </el-checkbox-group>
    <div class="role-btns">
      <el-button type="primary" round @click="onSubmit">确定</el-button>
      <el-button round @click="cancel">取消</el-button>
    </div>
  </div>
</template>
<script>
import { getRolesListRequest } from '@/api/setting'
import { userAssignRolesRequest, userInfoDetailRequest } from '@/api/user'

export default {
  name: 'AssignRoleCom',
  props: {
    currentId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      checkList: [],
      list: []
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      try {
        const res = await getRolesListRequest({ page: 1, pagesize: 1000 })
        if (res.success) {
          this.list = res.data.rows
        } else {
          this.$message.error(res.message)
        }

        const res2 = await userInfoDetailRequest(this.currentId)
        if (res2.success) {
          this.checkList = res2.data.roleIds || []
          // this.checkList = null
        } else {
          // 一般为了防止后端返回的数据没有message属性，提示就会为空，用户体验不好
          // 使用逻辑中断，提示用户体验，先展示后端的错误消息，在显示前端兜底的错误信息
          this.$message.error(res2.message || '根据id获取用户信息的接口失败')
        }
      } catch (error) {
        this.$message.error('获取角色列表失败')
      }
    },
    cancel() {
      this.$emit('close')
    },
    async onSubmit() {
      try {
        const res = await userAssignRolesRequest({
          id: this.currentId,
          roleIds: this.checkList
        })
        if (res.success) {
          // 关闭弹出框
          this.cancel()
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        console.log('userAssignRolesRequest: ', err)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.role-btns {
    text-align: right;
}
</style>
